package com.parkinginfo.manager;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import com.google.android.maps.GeoPoint;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class GarageObject 
{
	//Constants
    private static final String INCREMENTAL_STR = "Incremental";
    private static final String BEGIN_TIME  = "BEG";
    private static final String END_TIME  = "END";
    private static final String RATE = "RATE";
    private static final String RQ_STRING   = "RQ";
    private static final String OPER_KEY  = "OPER";
    private static final String OCC_KEY   = "OCC";
    private static final String DESC_KEY  = "DESC";
    private static final String RATES_KEY = "RATES";
    private static final String TYPE_KEY  = "TYPE";
    private static final String RS_KEY    = "RS";
    private static final String RATE_KEY  = "RATE";
    private static final String LOCATION   = "LOC";
    private static final String NAME_KEY  = "NAME";   
    private static final String INTER_SECTION = "INTER";
    private static final String TELEPHONE = "TEL";
    private static final String OPER_HRS = "OPHRS";

    public JSONObject TheGarageInformation;
    
    public GeoPoint   nw;
    public GeoPoint   se;
    public float      lat1,lon1,lat2,lon2;
    
    //These are garage details
    public int	  uniqueID;
    
    public String	  Address;
    public String interSection = "Not Available";
    public String desc = "Not Available";
    public String telephone = "Not Available";
    
    public GeoPoint   mid;
    public double latti;
    public double longi;
    
    
    public String	  type;
    public boolean onStreet;
    
    //spaces available
    public int used_spaces;
    public int total_capacity;
    public int available_spaces;
    
    //Rates String...shows Details about the rates
    public String ratesDetails;
    
    //operational hours
    public String hoursDetails;
    
    public float      currentCharge;
    public String     typeOfCharge;
   
    public String rate_test;
    public String     beg,end,rq;
      
    

    public GarageObject(int id)
    {
    	uniqueID = id;
    }
    
    public boolean parseJSONData() throws JSONException 
    {
        if (TheGarageInformation == null) {
            return false;
        }

        onStreet = false;
        beg			  = null;		
        end			  = null;		
        rate_test		  = null;       
        rq			  = null;      
        currentCharge  = 0;
        typeOfCharge = "";
        
        
        // get the Address, intersection, telephone
        Address = TheGarageInformation.getString(NAME_KEY);
        interSection = TheGarageInformation.optString(INTER_SECTION, null);
        desc = TheGarageInformation.optString(DESC_KEY, null);
        telephone = TheGarageInformation.optString(TELEPHONE, null);

        
        // get the location
        String loc = TheGarageInformation.getString(LOCATION);
        String[] params = loc.split(",");

        GeoPoint point1;
        GeoPoint point2;

        lon1 = Float.parseFloat(params[0]);
        lat1 = Float.parseFloat(params[1]);

        point1 = GoogleParkingActivity.getPoint(lat1,lon1);
        nw = point1;
        se = point1;
        mid = point1;
        if (params.length == 4) 
        {
            lon2 = Float.parseFloat(params[2]);
            lat2 = Float.parseFloat(params[3]);

            point2 = GoogleParkingActivity.getPoint(lat2,lon2);
            se = point2;
            latti = (lat1 + lat2)/2;
            longi = (lon1 + lon2)/2;
            mid = GoogleParkingActivity.getPoint((lat1 + lat2)/2,(lon1 + lon2)/2);
        }

        
        // get the type of the Garage.
        type = TheGarageInformation.optString(TYPE_KEY);
        	if(type.equals("ON"))
        	{
        		type = "On the Street";
        		onStreet = true;
        	}
        	else
        	{
        		type = "Garage";
        		onStreet = false;
        	}
        
        // get the used, available spaces and total spaces 
        used_spaces = TheGarageInformation.optInt(OCC_KEY,0);
        total_capacity = TheGarageInformation.optInt(OPER_KEY,0);
        available_spaces = total_capacity - used_spaces;
        
        //get rates and operational hours
        this.getRatesDetails();
        this.getOperationHours();
        
        //get the rates
        JSONObject rates = TheGarageInformation.optJSONObject(RATES_KEY);
        if (rates != null) {
            JSONArray  rateArray = rates.optJSONArray(RS_KEY);
            if (!(rateArray == null)) 
            {
                boolean isDynamicPricing = true;
                int rsc = rateArray.length();
                for (int i =0; i < rsc; i++) 
                {
                    JSONObject rateObject = rateArray.getJSONObject(i);
                    float phr = (float)rateObject.optDouble(RATE_KEY, 0);
                    String description = rateObject.optString(DESC_KEY);
                    //this is for price per hour...
                    if (description != null) 
                    	{
                        if (description.contains(INCREMENTAL_STR)) 
                        {
                        	System.out.println("not incremental :" + phr);
                            isDynamicPricing = false;
                            currentCharge = phr;
                            break;
                        }
                    }
                }
                if (isDynamicPricing) 
                	{
                	System.out.println("Incremental");
                    for (int i =0; i < rsc; i++) 
                    	{
                        JSONObject rateObject = rateArray.getJSONObject(i);
                        float phr = (float)rateObject.optDouble(RATE_KEY, 0);
                        rateStructureHandle(rateObject);
                        if (currentDynamicRate(beg,end)) 
                        {
                            currentCharge = phr;
                            break;
                        }
                    }
                }
            }
        }
        typeOfCharge = rq;
        return true;
    }
    
    // Update properties of start and end times for the current rate.
    public void rateStructureHandle(JSONObject rateJSONObject) 
    {
        beg	 = rateJSONObject.optString(BEGIN_TIME,  null);
        end	 = rateJSONObject.optString(END_TIME,  null);
        rate_test = rateJSONObject.optString(RATE, null);
        rq	 = rateJSONObject.optString(RQ_STRING, null);
    }
    
    
    //get the current rates for the garage
    public boolean currentDynamicRate(String begTimeString, String endTimeString) 
    {
    	System.out.println("calculate current dynamic rate.");
        if (begTimeString == null || endTimeString == null) 
        {
            return false;
        }
        if (endTimeString.equals("12:00 AM")) 
        {
            endTimeString = "11:59 PM";
        }
        String begTime = begTimeString.substring(0, begTimeString.length()-3);
        String[] endTime = begTime.split(":");

        //Begine Time Hours
        int hours = Integer.valueOf(endTime[0]);
        //convert to 24 hour time
        if (begTimeString.endsWith("AM") && (hours == 12)) 
        {
            hours = 0;
        }
        if (begTimeString.endsWith("PM") && (hours != 12)) 
        {
            hours = hours + 12;
        }
        //Begin Time Minutes
        int minutes = Integer.valueOf(endTime[1]);
        int begTimeMinutes = (hours * 60) + minutes;

        begTime = endTimeString.substring(0, endTimeString.length()-3);
        endTime = begTime.split(":");

        
        
        //End Time Hours
        hours = Integer.valueOf(endTime[0]);
        // convert to 24 hour
        if (endTimeString.endsWith("AM") && (hours == 12)) 
        {
            hours = 0;
        }
        if (endTimeString.endsWith("PM") && (hours != 12)) 
        {
            hours = hours + 12;
        }
        //Begin Time minutes
        minutes = Integer.valueOf(endTime[1]);
        int endTimeMinutes = (hours * 60) + minutes;

        
        // Get the current time
        SimpleDateFormat date_format = new SimpleDateFormat( "yyyy-MM-dd'T'H:mm:ss'.'SSSZZZZ" );
        try {
        	GoogleParkingActivity.timeStamp = date_format.parse(GoogleParkingActivity.timeStampXML);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        SimpleDateFormat formating = new SimpleDateFormat("h:mma");
        String currentTime = formating.format(GoogleParkingActivity.timeStamp);

        //convert time stamp to minutes. String now is 24 hour time display.
        SimpleDateFormat formating24 = new SimpleDateFormat("HH:mm");
        String currentTime24 = formating24.format(GoogleParkingActivity.timeStamp);
        String[] mytime = currentTime24.split(":");
        
        int current_hours = Integer.valueOf(mytime[0]);
        int current_minutes = Integer.valueOf(mytime[1]);

        // for price bucket calculations
        GoogleParkingActivity.timeStampMinutes = (current_hours * 60) + current_minutes;
        
        if ((GoogleParkingActivity.timeStampMinutes >= begTimeMinutes)
            && (GoogleParkingActivity.timeStampMinutes < endTimeMinutes)) 
        	{
            return true;
        	}

        return false;
    }
    
    public String getOperationHours()
    {
     String result = "Operational Hours Details: ";
   	 JSONObject operational = TheGarageInformation.optJSONObject("OPHRS");
        if (operational != null)
        {
        JSONArray  rateArray = operational.optJSONArray("OPS");
        if (!(rateArray == null)) 
        	{
            int rsc = rateArray.length();
            for(int i =0; i < rsc; i++) 
            {
                JSONObject rateObject = null;
				try {
					rateObject = rateArray.getJSONObject(i);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
                String from = rateObject.optString("FROM");
                String to	 = rateObject.optString("TO");
                String begin	 = rateObject.optString("BEG");
                String end = rateObject.optString("END");
                
                result += '\n' + "(" + (i+1) + ")" + " From: " + from + ", To: " + to
               	 + ", Begin: " + begin + ",End " + end;
        	}
        }
       }
        hoursDetails = result;
        System.out.println(result);
        return result;
    }
    
    public String getRatesDetails()
    {
    	String result = "Rate Details: ";
    	 JSONObject rates = TheGarageInformation.optJSONObject(RATES_KEY);
         if (rates != null)
         {
         JSONArray  rateArray = rates.optJSONArray(RS_KEY);
         if (!(rateArray == null)) 
         	{
             int rsc = rateArray.length();
             for (int i =0; i < rsc; i++) 
             {
                 JSONObject rateObject = null;
				try {
					rateObject = rateArray.getJSONObject(i);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
                 float phr = (float)rateObject.optDouble(RATE_KEY, 0);
                 String description = rateObject.optString(DESC_KEY);
                 String beg	 = rateObject.optString(BEGIN_TIME,  null);
                 String end	 = rateObject.optString(END_TIME,  null);
                 String rate = rateObject.optString(RATE, null);
                 rq	 = rateObject.optString(RQ_STRING, null);
                 
                 result += '\n' + "(" + (i+1) + ")" + " Begin Time: " + beg + ", End Time: " + end
                	 + ", Rate: $" + rate + ", Type: " + rq;
         	}
         }
        }
    ratesDetails = result;
    System.out.println(result);
    return result;
    }

}